/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean.session;

import entity.PickingOrderEntity;
import entity.SystemUserEntity;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import util.Fixtures.Department;

/**
 *
 * @author wei
 */
@Stateless
public class PickingOrderEntityFacade extends AbstractFacade<PickingOrderEntity> {

    @PersistenceContext(unitName = "MacTeam-warPU")
    private EntityManager em;
    @Resource
    SessionContext ctx;
    @EJB
    private DepartmentEntityFacade departmentFacade;
    @EJB
    private InternalMessageEntityFacade messageFacade;

    protected EntityManager getEntityManager() {
        return em;
    }

    public PickingOrderEntityFacade() {
        super(PickingOrderEntity.class);
    }

    public void scheduleTimer(Date validity, long id) {
        Timer timer = ctx.getTimerService().createTimer(validity, id);
      
        System.out.println("Time Remaining"+timer.getTimeRemaining());
    }

    @Timeout
    public void createSchedule() {
        System.out.println("IN TIMER");
        Date currentDate = new Date();
        List<PickingOrderEntity> pickingOrders = new ArrayList<PickingOrderEntity>(this.findAll());
        System.out.println("Pickingorders size"+pickingOrders.size());
        
        SystemUserEntity warehouseManager = departmentFacade.findDepartmentByName(Department.Warehouse.getName()).getManager();
        System.out.println("WArehousemanager name"+warehouseManager.getId());
        for (PickingOrderEntity pickingOrder : pickingOrders) {
            System.out.println(currentDate+"currentdate");
            System.out.println(pickingOrder.getPickDate()+"pickdate");
            if (pickingOrder.getPickDate().equals(currentDate) || pickingOrder.getPickDate().before(currentDate)) {
                messageFacade.createAndSendSystemMessage(warehouseManager, "Picking Order #" + pickingOrder.getId() + " needs to be picked today.",
                        "/entities/pickingOrderEntity/List.xhtml", null);
            }
        }
    }
}
